package com.figure.core.service.impl.item;

import com.figure.common.utils.DateUtil;
import com.figure.common.utils.StringUtil;
import com.figure.core.dao.item.*;
import com.figure.core.model.item.*;
import com.figure.core.top.product.Product;
import com.figure.service.constant.ItemInTypeConstant;
import com.figure.service.constant.StatusConstant;
import com.figure.service.dto.PageDto;
import com.figure.service.dto.item.*;
import com.figure.service.provide.item.IItemService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taobao.api.ApiException;
import com.taobao.api.domain.AitaobaoItem;
import com.taobao.api.response.AtbItemsCouponGetResponse;
import com.taobao.api.response.AtbItemsGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by chuanbo.wei on 2016/8/31.
 */
@Service("itemService")
public class ItemServiceImpl implements IItemService {

    private static Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);
    private static Long pageSize = 50l;

    @Autowired
    AtbItemMapper atbItemMapper;

    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    HotItemMapper hotItemMapper;

    @Autowired
    RecommendItemMapper recommendItemMapper;

    @Autowired
    FigureItemMapper figureItemMapper;

    @Autowired
    FigureCategoryMapper figureCategoryMapper;

    /**
     * taobao.atb.items.get (爱淘宝商品查询)
     * @param area  商品所在地
     * @param autoSend  是否自动发货
     * @param cashCoupon 是否支持抵价券，设置为true表示该商品支持抵价券，设置为false或不设置表示不判断这个属性
     * @param cid   标准商品后台类目id。该ID可以通过taobao.itemcats.get接口获取到。
     * @param endCommissionNum  30天累计推广量（与返回数据中的commission_num字段对应）上限.
     * @param endCommissionRate 佣金比率上限，如：2345表示23.45%。注：start_commissionRate和end_commissionRate一起设置才有效。
     * @param endCredit 可选值和start_credit一样.start_credit的值一定要小于或等于end_credit的值。注：end_credit与start_credit一起使用才生效
     * @param endPrice  最高价格
     * @param endTotalnum   商品总成交量（与返回字段volume对应）上限。
     * @param fields    需返回的字段列表.可open_iid,title,nick,pic_url,price,commission,commission_rate,commission_num,commission_volume,seller_credit_score,item_location,volume,seller_id,title,coupon_rate,coupon_price,coupon_start_time,coupon_end_time,shop_type,promotion_price
     * @param guarantee 是否查询消保卖家
     * @param keyword   商品标题中包含的关键字. 注意:查询时keyword,cid至少选择其中一个参数
     * @param mallItem  是否商城的商品，设置为true表示该商品是属于淘宝商城的商品，设置为false或不设置表示不判断这个属性
     * @param onemonthRepair    是否30天维修，设置为true表示该商品是支持30天维修，设置为false或不设置表示不判断这个属性
     * @param overseasItem  是否海外商品，设置为true表示该商品是属于海外商品，默认为false
     * @param pageNo    结果页数.1~10 支持最大值为：10
     * @param pageSize  每页返回结果数.最大每页40 支持最大值为：400
     * @param realDescribe  是否如实描述(即:先行赔付)商品，设置为true表示该商品是如实描述的商品，设置为false或不设置表示不判断这个属性
     * @param sevendaysReturn   是否支持7天退换，设置为true表示该商品支持7天退换，设置为false或不设置表示不判断这个属性
     * @param sort  默认排序:default price_desc(价格从高到低) price_asc(价格从低到高) credit_desc(信用等级从高到低)
     *              commissionRate_desc(佣金比率从高到低) commissionRate_asc(佣金比率从低到高) commissionNum_desc(成交量成高到低)
     *              commissionNum_asc(成交量从低到高) commissionVolume_desc(总支出佣金从高到低)
     *              commissionVolume_asc(总支出佣金从低到高) delistTime_desc(商品下架时间从高到低) delistTime_asc(商品下架时间从低到高)
     * @param startCommissionNum    30天累计推广量（与返回数据中的commission_num字段对应）下限.注：该字段要与end_commissionNum一起使用才生效
     * @param startCommissionRate   佣金比率下限，如：1234表示12.34%
     * @param startCredit   卖家信用: 1heart(一心) 2heart (两心) 3heart(三心) 4heart(四心) 5heart(五心) 1diamond(一钻) 2diamond(两钻 3diamond(三钻)
     *                      4diamond(四钻) 5diamond(五钻) 1crown(一冠) 2crown(两冠) 3crown(三冠) 4crown(四冠) 5crown(五冠)
     *                      1goldencrown(一黄冠) 2goldencrown(二黄冠) 3goldencrown(三黄冠) 4goldencrown(四黄冠) 5goldencrown(五黄冠)
     * @param startPrice    起始价格.传入价格参数时,需注意起始价格和最高价格必须一起传入,并且 start_price <= end_price
     * @param startTotalnum 商品总成交量（与返回字段volume对应）下限。
     * @param supportCod    是否支持货到付款，设置为true表示该商品是支持货到付款，设置为false或不设置表示不判断这个属性
     * @param vipCard   是否支持VIP卡，设置为true表示该商品支持VIP卡，设置为false或不设置表示不判断这个属性
     * @return
     */
    @Override
    public int addAtbItems(String area, String autoSend, String cashCoupon, Long cid, String endCommissionNum,String endCommissionRate,String endCredit,
                            String endPrice,String endTotalnum,String fields,String guarantee,String keyword,String mallItem,
                            String onemonthRepair,String overseasItem,Long pageNo, Long pageSize, String realDescribe,String sevendaysReturn,
                            String sort,String startCommissionNum,String startCommissionRate,String startCredit,String startPrice,
                            String startTotalnum,String supportCod, String vipCard){
        Product product = new Product();
        AtbItemsGetResponse s = null;
        try {
            s = product.getAtbItems(area, autoSend,cashCoupon,cid,endCommissionNum,endCommissionRate,endCredit,endPrice,endTotalnum
                    ,fields,
                    guarantee,keyword,mallItem,onemonthRepair,overseasItem,pageNo, pageSize,realDescribe,sevendaysReturn,
                    sort,startCommissionNum,startCommissionRate,startCredit,startPrice,startTotalnum,supportCod,vipCard);
        } catch (ApiException e) {
//            logger.error("getAtbItems error page num is 1");
            e.printStackTrace();
        }

        if(null==s || s.getTotalResults()<=0)
            return 0;
        Long total = s.getTotalResults();
        Long pages = total/pageSize;
        if(total%pageSize>0){
            pages = pages+1;
        }
        Thread thread = new Thread(new ItemImportExecut(area, autoSend, cashCoupon, cid, endCommissionNum, endCommissionRate, endCredit, endPrice, endTotalnum
                , fields,
                guarantee, keyword, mallItem, onemonthRepair, overseasItem, pageNo, pageSize, realDescribe, sevendaysReturn,
                sort, startCommissionNum, startCommissionRate, startCredit, startPrice, startTotalnum, supportCod, vipCard,pages));
        thread.setDaemon(true);
        thread.start();

        int insertTotal = 0;
//        Long num = pageNo;
//        List<AtbItem> list = null;
//        do {
//            try {
//                s = product.getAtbItems(null, null,null,null,null,null,null,null,null
//                        ,"open_iid,title,nick,pic_url,price,commission,commission_rate,commission_num,commission_volume,seller_credit_score,item_location,volume,seller_id,title,coupon_rate,coupon_price,coupon_start_time,coupon_end_time,shop_type,promotion_price",
//                        "true","动漫",null,null,null,num, pageSize,null,null,
//                        null,null,null,null,null,null,null,null);
//                list = new ArrayList<AtbItem>();
//                AtbItem atbItem;
//                for(AitaobaoItem item : s.getItems()){
//                    atbItem = new AtbItem();
//                    atbItem.setOpenIid(item.getOpenIid());
//                    atbItem.setCommission(null==item.getCommission()?new Double(0):new Double(item.getCommission()));
//                    atbItem.setCommissionNum(null==item.getCommissionNum()?0:new Long(item.getCommissionNum()));
//                    atbItem.setCommissionRate(null==item.getCommissionRate()?new Double(0):new Double(item.getCommissionRate()));
//                    atbItem.setCommissionVolume(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
//                    atbItem.setCouponEndTime(null==item.getCouponEndTime()?null: DateUtil.strToDate(item.getCouponEndTime(),"yyyy-MM-dd HH:mm:ss"));
//                    atbItem.setCouponPrice(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
//                    atbItem.setCouponRate(null==item.getCouponRate()?new Double(0):new Double(item.getCouponRate()));
//                    atbItem.setCouponStartTime(null==item.getCouponStartTime()?null: DateUtil.strToDate(item.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
//                    atbItem.setItemLocation(item.getItemLocation());
//                    atbItem.setNick(item.getNick());
//                    atbItem.setPicUrl(item.getPicUrl());
//                    atbItem.setPrice(null==item.getPrice()?new Double(0):new Double(item.getPrice()));
//                    atbItem.setVolume(item.getVolume());
//                    atbItem.setTitle(item.getTitle());
//                    atbItem.setShopType(item.getShopType());
//                    atbItem.setSellerId(item.getSellerId());
//                    atbItem.setSellerCreditScore(null==item.getSellerCreditScore()?0:item.getSellerCreditScore().intValue());
//                    atbItem.setPromotionPrice(null==item.getPromotionPrice()?new Double(0):new Double(item.getPromotionPrice()));
//                    list.add(atbItem);
//                }
//                atbItemMapper.insertBatch(list);
//                insertTotal =+ list.size();
//                num++;
////                try {
////                    Thread.sleep(3000);
////                } catch (InterruptedException e) {
////                    e.printStackTrace();
////                }
//            } catch (ApiException e) {
//                e.printStackTrace();
////                logger.error("getAtbItems error page num is " + num);
//            }
//        }while (num<=pages.intValue());
        return insertTotal;
    }

    @Override
    public PageDto<AtbItemDto> getAtbItems(String area, String autoSend, String cashCoupon, Long cid, String endCommissionNum,
                           String endCommissionRate, String endCredit, String endPrice, String endTotalnum, String fields,
                           String guarantee, String keyword, String mallItem, String onemonthRepair, String overseasItem,
                           Long pageNo, Long pageSize, String realDescribe, String sevendaysReturn, String sort, String startCommissionNum,
                           String startCommissionRate, String startCredit, String startPrice, String startTotalnum, String supportCod, String vipCard) {
        Product product = new Product();
        AtbItemsGetResponse s = null;
        List<AtbItemDto> list = null;
        try {
            s = product.getAtbItems(area, autoSend,cashCoupon,cid,endCommissionNum,endCommissionRate,endCredit,endPrice,endTotalnum
                    ,fields,
                    guarantee,keyword,mallItem,onemonthRepair,overseasItem,pageNo, pageSize,realDescribe,sevendaysReturn,
                    sort,startCommissionNum,startCommissionRate,startCredit,startPrice,startTotalnum,supportCod,vipCard);
            if(null==s || s.getTotalResults()<=0)
                return null;
            Long total = s.getTotalResults();
            Long pages = total/pageSize;
            if(total%pageSize>0){
                pages = pages+1;
            }
            list = new ArrayList<AtbItemDto>();
            AtbItemDto atbItem;
            for(AitaobaoItem item : s.getItems()){
                atbItem = new AtbItemDto();
                atbItem.setOpenIid(item.getOpenIid());
                atbItem.setCommission(null==item.getCommission()?new Double(0):new Double(item.getCommission()));
                atbItem.setCommissionNum(null==item.getCommissionNum()?0:new Long(item.getCommissionNum()));
                atbItem.setCommissionRate(null==item.getCommissionRate()?new Double(0):new Double(item.getCommissionRate()));
                atbItem.setCommissionVolume(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                atbItem.setCouponEndTime(null==item.getCouponEndTime()?null: DateUtil.strToDate(item.getCouponEndTime(),"yyyy-MM-dd HH:mm:ss"));
                atbItem.setCouponPrice(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                atbItem.setCouponRate(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                atbItem.setCouponStartTime(null==item.getCouponStartTime()?null: DateUtil.strToDate(item.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
                atbItem.setItemLocation(item.getItemLocation());
                atbItem.setNick(item.getNick());
                atbItem.setPicUrl(item.getPicUrl());
                atbItem.setPrice(null==item.getPrice()?new Double(0):new Double(item.getPrice()));
                atbItem.setVolume(item.getVolume());
                atbItem.setTitle(item.getTitle());
                atbItem.setShopType(item.getShopType());
                atbItem.setSellerId(item.getSellerId());
                atbItem.setSellerCreditScore(null==item.getSellerCreditScore()?0:item.getSellerCreditScore().intValue());
                atbItem.setPromotionPrice(null==item.getPromotionPrice()?new Double(0):new Double(item.getPromotionPrice()));
                list.add(atbItem);
            }
            return new PageDto(pageNo.intValue(),pageSize.intValue(),total, pages.intValue(),list);
        } catch (ApiException e) {
//            logger.error("getAtbItems error page num is 1");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addAtbItemsCoupon(String area,Long cid, Long couponType, Long endCommissionNum,Long endCommissionRate,Long endCommissionVolume,Long endCouponRate,
                           String endCredit,Long endVolume,String fields,String keyword,Long pageNo, Long pageSize, String shopType,
                           String sort,Long startCommissionNum,Long startCommissionRate,Long startCommissionVolume,Long startCouponRate,
                           String startCredit,Long startVolume){
        Product product = new Product();
        AtbItemsCouponGetResponse s = null;
        try {
            s = product.getAtbItemsCoupon(area,cid,couponType,endCommissionNum,endCommissionRate,endCommissionVolume,endCouponRate,endCredit,endVolume,
                    fields,keyword,pageNo, pageSize,shopType,
                    sort,startCommissionNum,startCommissionRate,startCommissionVolume,startCouponRate,startCredit,startVolume);
        } catch (ApiException e) {
//            logger.error("getAtbItems error page num is 1");
            e.printStackTrace();
        }
        if(null==s) {
            logger.info(keyword + " select item is null.");
            return 0;
        }
        logger.info(s.getErrorCode() + ":" + s.getMsg() + ">>>>" + s.getSubCode() + ":" + s.getSubMsg());
        Long total = s.getTotalResults();
        Long pages = total/pageSize;
        if(total%pageSize>0){
            pages = pages+1;
        }

        int insertTotal = 0;

        return insertTotal;
    }

    class ItemImportExecut implements Runnable{
        String area;
        String autoSend;
        String cashCoupon;
        Long cid;
        String endCommissionNum;
        String endCommissionRate;
        String endCredit;
        String endPrice;
        String endTotalnum;
        String fields;
        String guarantee;
        String keyword;
        String mallItem;
        String onemonthRepair;
        String overseasItem;
        Long pageNo;
        Long pageSize;
        String realDescribe;
        String sevendaysReturn;
        String sort;
        String startCommissionNum;
        String startCommissionRate;
        String startCredit;
        String startPrice;
        String startTotalnum;
        String supportCod;
        String vipCard;
        Long pages;
        public ItemImportExecut(String area, String autoSend, String cashCoupon, Long cid, String endCommissionNum,String endCommissionRate,String endCredit,
                                String endPrice,String endTotalnum,String fields,String guarantee,String keyword,String mallItem,
                                String onemonthRepair,String overseasItem,Long pageNo, Long pageSize, String realDescribe,String sevendaysReturn,
                                String sort,String startCommissionNum,String startCommissionRate,String startCredit,String startPrice,
                                String startTotalnum,String supportCod, String vipCard, Long pages){
            this.area = area;
            this.autoSend=autoSend;
            this.cashCoupon=cashCoupon;
            this.cid=cid;
            this.endCommissionNum=endCommissionNum;
            this.endCommissionRate=endCommissionRate;
            this.endCredit=endCredit;
            this.endPrice=endPrice;
            this.endTotalnum=endTotalnum;
            this.fields=fields;
            this.guarantee=guarantee;
            this.keyword=keyword;
            this.mallItem=mallItem;
            this.onemonthRepair=onemonthRepair;
            this.overseasItem=overseasItem;
            this.pageNo=pageNo;
            this.pageSize=pageSize;
            this.realDescribe=realDescribe;
            this.sevendaysReturn=sevendaysReturn;
            this.sort=sort;
            this.startCommissionNum=startCommissionNum;
            this.startCommissionRate=startCommissionRate;
            this.startCredit=startCredit;
            this.startPrice=startPrice;
            this.startTotalnum=startTotalnum;
            this.supportCod=supportCod;
            this.vipCard=vipCard;
            this.pages=pages;
        }
        @Override
        public void run() {
            Long num = new Long(1);
            List<AtbItem> list = null;
            Product product = new Product();
            AtbItemsGetResponse s = null;
            while (num<=pages.intValue()) {
                try {
                    s = product.getAtbItems(area, autoSend, cashCoupon, cid, endCommissionNum, endCommissionRate, endCredit, endPrice, endTotalnum
                            , fields,
                            guarantee, keyword, mallItem, onemonthRepair, overseasItem, num, pageSize, realDescribe, sevendaysReturn,
                            sort, startCommissionNum, startCommissionRate, startCredit, startPrice, startTotalnum, supportCod, vipCard);
                    if(null==s || null==s.getItems() || s.getItems().size()<=0)
                        continue;
                    list = new ArrayList<AtbItem>();
                    AtbItem atbItem;
                    for(AitaobaoItem item : s.getItems()){
                        atbItem = new AtbItem();
                        atbItem.setOpenIid(item.getOpenIid());
                        atbItem.setCommission(null==item.getCommission()?new Double(0):new Double(item.getCommission()));
                        atbItem.setCommissionNum(null==item.getCommissionNum()?0:new Long(item.getCommissionNum()));
                        atbItem.setCommissionRate(null==item.getCommissionRate()?new Double(0):new Double(item.getCommissionRate()));
                        atbItem.setCommissionVolume(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                        atbItem.setCouponEndTime(null==item.getCouponEndTime()?null: DateUtil.strToDate(item.getCouponEndTime(),"yyyy-MM-dd HH:mm:ss"));
                        atbItem.setCouponPrice(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                        atbItem.setCouponRate(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
                        atbItem.setCouponStartTime(null==item.getCouponStartTime()?null: DateUtil.strToDate(item.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
                        atbItem.setItemLocation(item.getItemLocation());
                        atbItem.setNick(item.getNick());
                        atbItem.setPicUrl(item.getPicUrl());
                        atbItem.setPrice(null==item.getPrice()?new Double(0):new Double(item.getPrice()));
                        atbItem.setVolume(item.getVolume());
                        atbItem.setTitle(item.getTitle());
                        atbItem.setShopType(item.getShopType());
                        atbItem.setSellerId(item.getSellerId());
                        atbItem.setSellerCreditScore(null==item.getSellerCreditScore()?0:item.getSellerCreditScore().intValue());
                        atbItem.setPromotionPrice(null==item.getPromotionPrice()?new Double(0):new Double(item.getPromotionPrice()));
                        list.add(atbItem);
                    }
                    atbItemMapper.insertBatch(list);
                    num++;
                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    public List<BannerDto> getBannerDto() throws Exception {
        BannerExample example = new BannerExample();
        BannerExample.Criteria criteria =example.createCriteria();
        criteria.andStatusEqualTo(StatusConstant.OK.getValue());
        example.setOrderByClause(" create_time desc limit 0, 5 ");
        List<Banner> list = bannerMapper.selectByExample(example);
        if(null==list || list.size()<=0)
            return null;
        List<BannerDto> bannerDtos = new ArrayList<BannerDto>();
        BannerDto dto;
        for(Banner banner : list){
            dto = new BannerDto();
            dto.setImgUrl(banner.getImgUrl());
            dto.setId(banner.getId());
            dto.setName(banner.getName());
            dto.setType(banner.getType());
            dto.setContent(banner.getContent());
            bannerDtos.add(dto);
        }
        return bannerDtos;
    }

    @Override
    public PageDto<HotItemDto> getHotItems(int pageNo, int pageSize) throws Exception {
        PageHelper.startPage(pageNo, pageSize);
        HotItemExample example = new HotItemExample();
//        HotItemExample.Criteria criteria =example.createCriteria();
//        criteria.andStatusEqualTo(StatusConstant.OK.getValue());
        example.setOrderByClause(" create_time desc ");
        Page<HotItem> list = (Page<HotItem>)hotItemMapper.selectByExample(example);
        if(null==list || list.size()<=0)
            return null;
        List<HotItemDto> hotItemDtos = new ArrayList<HotItemDto>();
        HotItemDto dto;
        for(HotItem hotItem : list){
            dto = new HotItemDto();
            dto.setNick(hotItem.getNick());
            dto.setCategoryId(hotItem.getCategoryId());
            dto.setItemLocation(hotItem.getItemLocation());
            dto.setOpenIid(hotItem.getOpenIid());
            dto.setPicUrl(hotItem.getPicUrl());
            dto.setPrice(hotItem.getPrice());
            dto.setPromotionPrice(hotItem.getPromotionPrice());
            dto.setTitle(hotItem.getTitle());
            dto.setInType(hotItem.getInType());
            hotItemDtos.add(dto);
        }
        PageDto<HotItemDto> pageDto = new PageDto<HotItemDto>(list.getPageNum(), list.getPageSize(),
                list.getTotal(), list.getPages(), hotItemDtos);
        return pageDto;
    }

    @Override
    public PageDto<RecommendItemDto> getRecommendItems(int pageNo, int pageSize) throws Exception {
        PageHelper.startPage(pageNo, pageSize);
        RecommendItemExample example = new RecommendItemExample();
//        HotItemExample.Criteria criteria =example.createCriteria();
//        criteria.andStatusEqualTo(StatusConstant.OK.getValue());
        example.setOrderByClause(" create_time desc ");
        Page<RecommendItem> list = (Page<RecommendItem>)recommendItemMapper.selectByExample(example);
        if(null==list || list.size()<=0)
            return null;
        List<RecommendItemDto> recommendItemDtos = new ArrayList<RecommendItemDto>();
        RecommendItemDto dto;
        for(RecommendItem recommendItem : list){
            dto = new RecommendItemDto();
            dto.setNick(recommendItem.getNick());
            dto.setCategoryId(recommendItem.getCategoryId());
            dto.setItemLocation(recommendItem.getItemLocation());
            dto.setOpenIid(recommendItem.getOpenIid());
            dto.setPicUrl(recommendItem.getPicUrl());
            dto.setPrice(recommendItem.getPrice());
            dto.setPromotionPrice(recommendItem.getPromotionPrice());
            dto.setTitle(recommendItem.getTitle());
            dto.setInType(recommendItem.getInType());
            recommendItemDtos.add(dto);
        }
        PageDto<RecommendItemDto> pageDto = new PageDto<RecommendItemDto>(list.getPageNum(), list.getPageSize(),
                list.getTotal(), list.getPages(), recommendItemDtos);
        return pageDto;
    }

    @Override
    public PageDto<FigureItemDto> getFigureItems(int pageNo, int pageSize, String title, String orderType, Long categoryId) throws Exception {
        PageHelper.startPage(pageNo, pageSize);
//        FigureItemExample example = new FigureItemExample();
//        FigureItemExample.Criteria criteria =example.createCriteria();
//        criteria.andStatusEqualTo(StatusConstant.OK.getValue());
        //orderType 0:30天内交易量降序  1:卖家信用等级降序  2:促销价格升序 3:促销价格降序
//        if(StringUtil.isNotEmpty(title)){
//            title = "%" + title + "%";
//            criteria.andTitleLike(title);
//        }
//        if(null!=categoryId){
//            criteria.andCategoryIdEqualTo(categoryId);
//        }
//        if("1".equals(orderType)){
//            example.setOrderByClause(" seller_credit_score desc ");
//        }else if("2".equals(orderType)){
//            example.setOrderByClause(" promotion_price ");
//        }else if("3".equals(orderType)){
//            example.setOrderByClause(" promotion_price desc ");
//        }else{
//            example.setOrderByClause(" volume desc ");
//        }
        if(StringUtil.isEmpty(orderType)){
            orderType = "0";
        }
        Page<FigureItem> list = null;
        if(null==categoryId){
            list = (Page<FigureItem>)figureItemMapper.selectItemByCondition(title, orderType);
        }else {
            list = (Page<FigureItem>)figureItemMapper.selectByCondition(title, orderType, categoryId);
        }
        if(null==list || list.size()<=0)
            return null;
        List<FigureItemDto> figureItemDtos = new ArrayList<FigureItemDto>();
        FigureItemDto dto;
        for(FigureItem item : list){
            dto = new FigureItemDto();
            dto.setOpenIid(item.getOpenIid());
            dto.setCommission(null==item.getCommission()?new Double(0):new Double(item.getCommission()));
            dto.setCommissionNum(null==item.getCommissionNum()?0:new Long(item.getCommissionNum()));
            dto.setCommissionRate(null==item.getCommissionRate()?new Double(0):new Double(item.getCommissionRate()));
            dto.setCommissionVolume(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
            dto.setCouponEndTime(null==item.getCouponEndTime()?"": DateUtil.dateTimeToStr(item.getCouponEndTime(),"yyyy-MM-dd HH:mm:ss"));
            dto.setCouponPrice(null==item.getCouponPrice()?new Double(0):new Double(item.getCouponPrice()));
            dto.setCouponRate(null==item.getCouponRate()?new Double(0):new Double(item.getCouponRate()));
            dto.setCouponStartTime(null==item.getCouponStartTime()?"": DateUtil.dateTimeToStr(item.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
            dto.setItemLocation(item.getItemLocation());
            dto.setNick(item.getNick());
            dto.setPicUrl(item.getPicUrl());
            dto.setPrice(null==item.getPrice()?new Double(0):new Double(item.getPrice()));
            dto.setVolume(item.getVolume());
            dto.setTitle(item.getTitle());
            dto.setShopType(item.getShopType());
            dto.setSellerId(item.getSellerId());
            dto.setSellerCreditScore(null==item.getSellerCreditScore()?0:item.getSellerCreditScore().intValue());
            dto.setPromotionPrice(null==item.getPromotionPrice()?new Double(0):new Double(item.getPromotionPrice()));
            dto.setCategoryId(item.getCategoryId());
            dto.setInType(item.getInType());

            figureItemDtos.add(dto);
        }
        PageDto<FigureItemDto> pageDto = new PageDto<FigureItemDto>(list.getPageNum(), list.getPageSize(),
                list.getTotal(), list.getPages(), figureItemDtos);
        return pageDto;
    }

    @Override
    public void saveItemCategory(List<FigureItemDto> list, Long[] categoryIds) throws Exception {
        if(null==list || list.size()<=0)
            return;
        List<FigureItem> figureItems = new ArrayList<FigureItem>();
        List<FigureCategory> figureCategories = new ArrayList<FigureCategory>();
        FigureItem item;
        for(FigureItemDto dto : list){
            if(null==dto)
                continue;
            item = new FigureItem();
            item.setOpenIid(dto.getOpenIid());
            item.setCommission(dto.getCommission());
            item.setCommissionNum(dto.getCommissionNum());
            item.setCommissionRate(dto.getCommissionRate());
            item.setCommissionVolume(dto.getCommissionVolume());
            item.setCouponEndTime(null==dto.getCouponEndTime()?null: DateUtil.strToDateTime(dto.getCouponEndTime(), "yyyy-MM-dd HH:mm:ss"));
            item.setCouponPrice(dto.getCouponPrice());
            item.setCouponRate(dto.getCouponRate());
            item.setCouponStartTime(null==dto.getCouponStartTime()?null: DateUtil.strToDateTime(dto.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
            item.setItemLocation(dto.getItemLocation());
            item.setNick(dto.getNick());
            item.setPicUrl(dto.getPicUrl());
            item.setPrice(dto.getPrice());
            item.setVolume(dto.getVolume());
            item.setTitle(dto.getTitle());
            item.setShopType(dto.getShopType());
            item.setSellerId(dto.getSellerId());
            item.setSellerCreditScore(dto.getSellerCreditScore());
            item.setPromotionPrice(dto.getPromotionPrice());
//            item.setCategoryId(categoryId);
            item.setInType(ItemInTypeConstant.ATK.getValue());
            figureItems.add(item);

            FigureCategory figureCategory;
            for (Long id : categoryIds){
                figureCategory = new FigureCategory();
                figureCategory.setCategoryId(id);
                figureCategory.setOpenIid(dto.getOpenIid());
                figureCategories.add(figureCategory);
            }
        }
        figureItemMapper.insertBatch(figureItems);
        figureCategoryMapper.insertBatch(figureCategories);
    }

    @Override
    public void saveHotItems(List<FigureItemDto> list) throws Exception {
        if(null==list || list.size()<=0){
            return;
        }
        List<HotItem> hotItems = new ArrayList<HotItem>();
        HotItem item;
        for(FigureItemDto dto : list){
            if(null==dto)
                continue;
            item = new HotItem();
            item.setNick(dto.getNick());
            item.setCategoryId(dto.getCategoryId());
            item.setItemLocation(dto.getItemLocation());
            item.setOpenIid(dto.getOpenIid());
            item.setPicUrl(dto.getPicUrl());
            item.setPrice(dto.getPrice());
            item.setPromotionPrice(dto.getPromotionPrice());
            item.setTitle(dto.getTitle());
            item.setInType(ItemInTypeConstant.ATK.getValue());
            item.setCreateTime(new Date());
            hotItems.add(item);
        }
        hotItemMapper.insertBatch(hotItems);
    }

    @Override
    public void saveRecommendItems(List<FigureItemDto> list) throws Exception {
        if(null==list || list.size()<=0){
            return;
        }
        List<RecommendItem> hotItems = new ArrayList<RecommendItem>();
        RecommendItem item;
        for(FigureItemDto dto : list){
            if(null==dto)
                continue;
            item = new RecommendItem();
            item.setNick(dto.getNick());
            item.setCategoryId(dto.getCategoryId());
            item.setItemLocation(dto.getItemLocation());
            item.setOpenIid(dto.getOpenIid());
            item.setPicUrl(dto.getPicUrl());
            item.setPrice(dto.getPrice());
            item.setPromotionPrice(dto.getPromotionPrice());
            item.setTitle(dto.getTitle());
            item.setInType(ItemInTypeConstant.ATK.getValue());
            item.setCreateTime(new Date());
            hotItems.add(item);
        }
        recommendItemMapper.insertBatch(hotItems);
    }

    @Override
    public void saveBanner(BannerDto dto) throws Exception {
        if(null==dto)
            return;
        Banner banner = new Banner();
        banner.setImgUrl(dto.getImgUrl());
//        banner.setId(banner.getId());
        banner.setName(dto.getName());
        banner.setType(dto.getType());
        banner.setContent(dto.getContent());
        banner.setCreateTime(new Date());
        banner.setStatus(dto.getStatus());
        if(null!=dto.getId()){
            banner.setId(dto.getId());
            bannerMapper.updateByPrimaryKey(banner);
        }else {
            bannerMapper.insert(banner);
        }
    }

    @Override
    public FigureItemDto getFigureItem(String openIid) throws Exception {
        FigureItem item = figureItemMapper.selectByPrimaryKey(openIid);
        if(null==item)
            return null;
        FigureItemDto dto = new FigureItemDto();
        dto.setOpenIid(item.getOpenIid());
        dto.setCommission(null==item.getCommission()?new Double(0):new Double(item.getCommission()));
        dto.setCommissionNum(null==item.getCommissionNum()?0:new Long(item.getCommissionNum()));
        dto.setCommissionRate(null==item.getCommissionRate()?new Double(0):new Double(item.getCommissionRate()));
        dto.setCommissionVolume(null==item.getCommissionVolume()?new Double(0):new Double(item.getCommissionVolume()));
        dto.setCouponEndTime(null==item.getCouponEndTime()?"": DateUtil.dateTimeToStr(item.getCouponEndTime(),"yyyy-MM-dd HH:mm:ss"));
        dto.setCouponPrice(null==item.getCouponPrice()?new Double(0):new Double(item.getCouponPrice()));
        dto.setCouponRate(null==item.getCouponRate()?new Double(0):new Double(item.getCouponRate()));
        dto.setCouponStartTime(null==item.getCouponStartTime()?"": DateUtil.dateTimeToStr(item.getCouponStartTime(),"yyyy-MM-dd HH:mm:ss"));
        dto.setItemLocation(item.getItemLocation());
        dto.setNick(item.getNick());
        dto.setPicUrl(item.getPicUrl());
        dto.setPrice(null==item.getPrice()?new Double(0):new Double(item.getPrice()));
        dto.setVolume(item.getVolume());
        dto.setTitle(item.getTitle());
        dto.setShopType(item.getShopType());
        dto.setSellerId(item.getSellerId());
        dto.setSellerCreditScore(null==item.getSellerCreditScore()?0:item.getSellerCreditScore().intValue());
        dto.setPromotionPrice(null==item.getPromotionPrice()?new Double(0):new Double(item.getPromotionPrice()));
        dto.setCategoryId(item.getCategoryId());
        dto.setInType(item.getInType());
        return dto;
    }
}
